package com.example.jasonsun.sharelib;

import android.app.Activity;
import android.os.Bundle;

import com.example.jasonsun.sharelib.config.ConfigSetter;
import com.example.jasonsun.sharelib.platform.SharePlatform;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;

/**
 * 新浪微博能通过网页和客户端登陆和分享， QQ能通过网页登陆, 不能通过网页分享， 微信不能通过网页登录和分享
 */
public class ShareInstance {
    public static final String KEY_OPEN_ID = "open_id";
    public static final int RESP_OK = 0;
    public static final int RESP_ERROR = -1;
    public static final int RESP_CANCEL = -2;

    /**
     * 微博微博分享接口实例
     */
    private IWeiboShareAPI mWeiboShareAPI = null;

    private static ShareInstance sShareInstance;
    private boolean isInited = false;
    private Activity mActivity;
    private Thread mThread;
    private Bundle mResBundle;
    private int mErrCode;
    private String mErrMessage;

    private ShareInstance() {
    }

    public static ShareInstance getInstance() {
        if (sShareInstance == null) {
            sShareInstance = new ShareInstance();
        }

        return sShareInstance;
    }

    public void init() {
        /*
        // 创建微博分享接口实例
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Cache.sina_app_key);

        // 注册第三方应用到微博客户端中，注册成功后该应用将显示在微博的应用列表中。
        // 但该附件栏集成分享权限需要合作申请，详情请查看 Demo 提示
        // NOTE：请务必提前注册，即界面初始化的时候或是应用程序初始化时，进行注册
        mWeiboShareAPI.registerApp();
        */
        isInited = true;
    }

    public void init(ConfigSetter config) {
    }

    /**
     * 登录
     *
     * @param platformId 要登录的平台
     * @param callback   call back
     */
    public void login(Activity activity, final SharePlatFormId platformId, final IGetResult callback) {
        if (hasTaskRunning()) {
            if (callback != null) {
                callback.onFailure(-1, mActivity.getString(R.string.wait_running));
            }
            return;
        }

        mActivity = activity;

        int platNo = getPlatNo(platformId);
        if (platNo == SharePlatform.WECHAT_CIRCLE) {
            platNo = SharePlatform.WECHAT_SESSION;
        }
        if (platNo == SharePlatform.QZONE) {
            platNo = SharePlatform.QQ_FRIENDS;
        }

        FakeActivity.startThisActivityForLogin(mActivity, platNo);

        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        break;
                    }
                }

                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            if (mResBundle != null) {
                                callback.onSuccess(mResBundle);
                            } else {
                                callback.onFailure(mErrCode, mErrMessage);
                            }
                        }
                    }
                });
            }
        });
        mThread.start();
    }

    /**
     * 分享网页
     *
     * @param platformID 要分享到的平台
     * @param title      title
     * @param desc       description or content
     * @param imgUrl     image url
     * @param webUrl     web url
     * @param callback   callback
     */
    public void shareWeb(Activity activity, final SharePlatFormId platformID, String title, String desc, String imgUrl,
                         String webUrl, final IGetResult callback) {
        if (hasTaskRunning()) {
            if (callback != null) {
                callback.onFailure(-1, mActivity.getString(R.string.wait_running));
            }
            return;
        }

        mActivity = activity;

        int platNo = getPlatNo(platformID);
        FakeActivity.startThisActivityForShare(mActivity, platNo, title, desc, imgUrl, webUrl);

        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        break;
                    }
                }

                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            if (mResBundle != null) {
                                callback.onSuccess(mResBundle);
                            } else {
                                callback.onFailure(mErrCode, mErrMessage);
                            }
                        }
                    }
                });
            }
        });
        mThread.start();
    }

    private int getPlatNo(SharePlatFormId id) {
        int platNo = -1;
        switch (id) {
            case WEIXIN_FRIENDS:
                platNo = SharePlatform.WECHAT_SESSION;
                break;
            case WEIXIN_CIRCLE:
                platNo = SharePlatform.WECHAT_CIRCLE;
                break;
            case QQ_FRINEDS:
                platNo = SharePlatform.QQ_FRIENDS;
                break;
            case QZONE:
                platNo = SharePlatform.QZONE;
                break;
            case XINLANG_WEIBO:
                platNo = SharePlatform.XINLANG_WEIBO;
                break;
            default:
                throw new IllegalArgumentException("platform wrong");
        }
        return platNo;
    }

    public interface IGetResult {

        void onSuccess(Bundle result);

        void onFailure(int errCode, String errMessage);
    }

    public enum SharePlatFormId {
        WEIXIN_FRIENDS, WEIXIN_CIRCLE, QQ_FRINEDS, QZONE, XINLANG_WEIBO;
    }

    public void receiveMessage(boolean isSuccess, Bundle bundle, int errCode, String errMsg) {
        bundle = null;
        errCode = 0;
        errMsg = null;
        if (isSuccess) {
            mResBundle = bundle;
            mErrCode = errCode;
            mErrMessage = errMsg;
        } else {
            mResBundle = null;
            mErrCode = errCode;
            mErrMessage = errMsg;
        }
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }
    }

    private boolean hasTaskRunning() {
        if (mThread != null) {
            return true;
        }

        return false;
    }
}
